<?php

namespace app\common\logic\common;

use app\common\helper\AliOss;
use app\common\model\Attachment;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\File;
use think\helper\Str;

class CommonLogic
{
    public static function makeOrderNo()
    {
        return date('YmdHis') . Str::random(6,1);
    }

    public static function upload($path)
    {
        $config = cache("config");
        $file = $_FILES["file"];
        if (!$file) {
            throwError("请选择文件");
        }
        $ext = strtolower(strrchr($file["name"],"."));
        if (!file_exists($path)) {
            mkdir($path,0777,true);
        }
        $name = md5(time() . Str::random(6)) . $ext;
        $name = $path . "/" . $name;
        $allows = ".pdf,.xls,.xlsx,.doc,.docx,.zip,.rar,.mp3,.mp4,.jpg,.jpeg,.gif,.png,.webp,.ppt,.pptx,.wps";
        $allows = explode(",",$allows);
        if (!in_array($ext,$allows)) {
            throwError("不允许上传的文件类型。");
        }

        if (!move_uploaded_file($file["tmp_name"],$name)) {
            throwError("上传失败");
        }

        $file_type = "o";
        if (in_array($ext,['.doc','.docx','.wps'])) {
            $file_type = "w";
        }
        if (in_array($ext,['.ppt','.pptx'])) {
            $file_type = "p";
        }
        if (in_array($ext,['.xls','.xlsx'])) {
            $file_type = "s";
        }
        if ($ext == '.pdf') {
            $file_type = "f";
        }
        $file_id = md5($name . time() . Str::random() . session('admin.id'));
        return [
            "path" => "/".$name,
            "file_name" => $file["name"],
            "size" => $file["size"],
            "type" => $file["type"],
            "ext" => $ext,
            "file_type" => $file_type,
            "file_id" => $file_id
        ];
    }

    public static function mergeChunk($savePath)
    {
        $config = cache('config');
        $data = input();
        $md5 = input("md5");
        $ext = input("ext");
        if (!is_dir($savePath)) {
            mkdir($savePath,0777,true);
        }
        $saveName = date("YmdHis") . rand(100000,999999) . ".{$ext}";
        if (!is_dir($savePath)) {
            mkdir($savePath);
        }
        $basePath = app()->getRuntimePath() . "chunk_temp";
        $filePath = $basePath . "/" . $md5;
        $chunk_id = 0;
        $files = [];

        if (is_dir($filePath)) {
            while (file_exists($filePath . "/" . $chunk_id)) {
                $files[] = $filePath . "/" .$chunk_id;
                $chunk_id ++;
            }
        } else {
            throwError();
        }
        $count = 0;
        foreach ($files as $file) {
            $_file = file_get_contents($file);
            $_res = file_put_contents($savePath . $saveName,$_file,FILE_APPEND);
            if ($_res) {
                unlink($file);
            } else {
                $count ++;
            }
        }
        $ext = ".{$ext}";
        $file_type = "o";
        if (in_array($ext,['.doc','.docx','.wps'])) {
            $file_type = "w";
        }
        if (in_array($ext,['.ppt','.pptx'])) {
            $file_type = "p";
        }
        if (in_array($ext,['.xls','.xlsx'])) {
            $file_type = "s";
        }
        if ($ext == '.pdf') {
            $file_type = "f";
        }

        if ($count == 0) {
            rmdir($filePath);
            $file_id = md5($savePath.$saveName . time() . Str::random() . session('admin.id'));
            return [
                "path" => "/".$savePath.$saveName,
                "file_name" => $saveName,
                "size" => $data['size'],
                "type" => $data["type"],
                "ext" => $ext,
                "file_type" => $file_type,
                "file_id" => $file_id
            ];
        } else {
            throwError();
        }
    }
    
    // 导出
    public static function export($data,$header = [])
    {
        $sp = new Spreadsheet();
        $sheet = $sp->getActiveSheet();
        $header = ["顾问名称","分配量","添加量","成交量"];
        foreach ($header as $key => $value) {
            $sheet->setCellValueByColumnAndRow($key + 1,1,$value);
        }
        $row = 2;
        foreach ($data as $key=>$value) {
            $sheet->setCellValueByColumnAndRow(1,$row,$value['real_name']);
            $sheet->setCellValueByColumnAndRow(2,$row,$value['total']['all']);
            $sheet->setCellValueByColumnAndRow(3,$row,$value['total']['add_count']."({$value['total']['add_lv']}%)");
            $sheet->setCellValueByColumnAndRow(4,$row,$value['total']['order_count']."({$value['total']['order_lv']}%)");
            $row ++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="统计.xlsx"');
        header('Cache-Control: max-age=0');
        $write = new Xlsx($sp);
        $write->save('php://output');
        $sp->disconnectWorksheets();
        unset($sp);
        exit;
    }
}